<template>
  <div class="print-container">
    <div class="bill-content" id="printSection">
      <!-- 标题 -->
      <h1 class="title">群兴寿服销账单</h1>

      <!-- 基本信息 -->
      <div class="basic-info">
        <div class="info-row">
          <div class="info-item">
            <span class="label">逝者姓名：</span>
            <span class="value-line">{{ formData.deceasedName }}</span>
          </div>
          <div class="info-item">
            <span class="label">性别：</span>
            <span class="value-line">{{ formData.deceasedGender }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <span class="label">服务日期：</span>
            <span class="value-line">{{ formData.serviceDate }}</span>
          </div>
          <div class="info-item">
            <span class="label">地点：</span>
            <span class="value-line">{{ formData.serviceLocation }}</span>
          </div>
        </div>
      </div>

      <!-- 费用明细表格 -->
      <div class="bill-table">
        <div class="table-title">殡仪收费项目明细</div>
        <table>
          <thead>
          <tr>
            <th width="80">
              <span>序号</span>
            </th>
            <th width="100">
              <span>类别</span>
            </th>
            <th width="150">
              <span>子类</span>
            </th>
            <th width="500">
              <span>项目</span>
            </th>
            <th width="100">
              <span>数量</span>
            </th>
            <th width="180">
              <span>单价</span>
            </th>
            <th width="200">
              <span>金额</span>
            </th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="(item, index) in tableData" :key="index">
            <td>
              <span>{{ index + 1 }}</span>
            </td>
            <td v-if="shouldShowCell(index, 'category')" :rowspan="getRowspan(index, 'category')">
              <span>{{ item.category }}</span>
            </td>
            <td v-if="shouldShowCell(index, 'subCategory')" :rowspan="getRowspan(index, 'subCategory')">
              <span>{{ item.subCategory }}</span>
            </td>
            <td class="text-left">
              <span>{{ item.name }}</span>
            </td>
            <td>
              <span>{{ item.quantity }}</span>
            </td>
            <td>
              <span>{{ item.price }}</span>
            </td>
            <td>
              <span>{{ item.quantity * item.price }}</span>
            </td>
          </tr>
          </tbody>
        </table>

        <div class="total-amount">
          <span>合计金额：{{ totalAmount }} 元</span>
        </div>
      </div>

      <!-- 底部信息 -->
      <div class="footer-info">
        <div class="payment-method">
          <span class="label">支付方式：</span>
          <span class="value-line">{{ formData.paymentMethod }}</span>
        </div>

        <div class="signature-row">
          <div class="signature-item">
            <span class="label2">家属：</span>
            <span class="value-line2">{{ formData.familyContact }}</span>
          </div>
          <div class="signature-item">
            <span class="label2">电话：</span>
            <span class="value-line2">{{ formData.familyPhone }}</span>
          </div>
        </div>

        <div class="signature-row">
          <div class="signature-item">
            <span class="label2">礼仪师：</span>
            <span class="value-line2">{{ formData.masterName }}</span>
          </div>
          <div class="signature-item">
            <span class="label2">电话：</span>
            <span class="value-line2">{{ formData.masterPhone }}</span>
          </div>
        </div>

        <div class="signature-row">
          <div class="signature-item">
            <span class="label2">家属签字：</span>
            <span class="value-line2"></span>
          </div>
        </div>

        <div class="remarks">
          承诺不以任何借口收取账单以外费用，以上费用均以人民币结算签字确认后特殊服务不退换。
        </div>

        <div class="contact">
          大连群兴寿服负责人(投诉)电话：15640904777
        </div>

        <div class="footer-btn">
          <el-button @click="onClose">取 消</el-button>
          <el-button type="primary" @click="handlePrint">打 印</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import print from 'vue-print-nb'

export default {
  name: 'BillPrint',
  props: {
    billData: Object
  },
  data() {
    return {
      formData: this.billData.formData,
      tableData: this.billData.tableData,
      totalAmount: this.billData.totalAmount,
      print: {
        id: 'printArea',
        popTitle: '打印', // 打印配置页上方标题
        extraHead: '', //最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: '', // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: '', // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: '', // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: '', // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        previewBeforeOpenCallback() {
        }, //预览窗口打开之前的callback（开启预览模式调用）
        previewOpenCallback() {
        }, // 预览窗口打开之后的callback（开启预览模式调用）
        beforeOpenCallback() {
        }, // 开启打印前的回调事件
        openCallback() {
          console.log('开始打印')
        }, // 调用打印之后的回调事件
        closeCallback() {
          console.log('关闭打印')
          window.addEventListener('onClose', () => {
            this.onClose()
          })
        }, //关闭打印的回调事件（无法确定点击的是确认还是取消）
        url: '',
        standard: '',
        extraCss: '',
      },
    }
  },
  directives: {
    print
  },
  methods: {
    // 判断是否显示单元格
    shouldShowCell(index, type) {
      const item = this.tableData[index]
      const prevItem = index > 0 ? this.tableData[index - 1] : null

      switch (type) {
        case 'category':
          return !prevItem || prevItem.category !== item.category
        case 'subCategory':
          return !prevItem ||
              prevItem.category !== item.category ||
              prevItem.subCategory !== item.subCategory
        case 'index':
          return !prevItem || prevItem.category !== item.category
        default:
          return true
      }
    },

    // 获取合并的行数
    getRowspan(index, type) {
      const item = this.tableData[index]
      let count = 1

      switch (type) {
        case 'category':
          // 计算相同类别的行数
          for (let i = index + 1; i < this.tableData.length; i++) {
            if (this.tableData[i].category === item.category) {
              count++
            } else {
              break
            }
          }
          break
        case 'subCategory':
          // 计算相同子类的行数
          for (let i = index + 1; i < this.tableData.length; i++) {
            if (this.tableData[i].category === item.category &&
                this.tableData[i].subCategory === item.subCategory) {
              count++
            } else {
              break
            }
          }
          break
        case 'index':
          // 序号与类别合并行数相同
          return this.getRowspan(index, 'category')
      }
      return count
    },
    onClose() {
      this.$emit('onClose')
    },
    handlePrint() {
      // 创建 iframe
      const printIframe = document.createElement('iframe');
      printIframe.style.position = 'absolute';
      printIframe.style.width = '0';
      printIframe.style.height = '0';
      printIframe.style.border = '0';
      document.body.appendChild(printIframe);

      // 获取打印内容
      const printContent = document.getElementById('printSection').innerHTML;

      // 写入打印内容
      const doc = printIframe.contentWindow.document;
      doc.write(`
        <!DOCTYPE html>
        <html>
          <head>
            <title>打印预览</title>
            <style>
              @page {
                size: A4;
                margin: 20mm;
              }
              body {
                margin: 0;
                padding: 0;
                font-family: SimSun, serif;
              }
              .bill-content {
                width: 100%;
              }
              .title {
                text-align: center;
                font-size: 24px;
                margin-bottom: 30px;
              }
              .basic-info {
                margin-bottom: 30px;
              }
              .info-row {
                display: flex;
                margin-bottom: 20px;
              }
              .info-item {
                flex: 1;
                display: flex;
                align-items: center;
              }
              .label {
                width: 100px;
                text-align: right;
                padding-right: 10px;
              }
              .value-line {
                flex: 1;
                height: 20px;
                border-bottom: 1px solid #000;
                padding: 0 5px;
                min-width: 150px;
              }
              .bill-table {
                margin-bottom: 30px;
              }
              .table-title {
                text-align: center;
                font-weight: bold;
                margin-bottom: 15px;
              }
              table {
                width: 100%;
                border-collapse: collapse;
              }
              th, td {
                border: 1px solid #000;
                text-align: center;
                padding: 8px;
                font-size: 14px;
              }
              .text-left {
                text-align: left;
              }
              .total-amount {
                text-align: right;
                margin-top: 15px;
                font-weight: bold;
              }
              .footer-info {
                margin-top: 30px;
              }
              .footer-btn {
                display: none;
              }
              .payment-method {
                margin-bottom: 20px;
              }
              .signature-row {
                display: flex;
                margin-bottom: 20px;
              }
              .signature-item {
                flex: 1;
                display: flex;
                align-items: center;
              }
              .label2 {
                width: 100px;
                text-align: right;
                padding-right: 10px;
              }
              .value-line2 {
                flex: 1;
                height: 20px;
                border-bottom: 1px solid #000;
                padding: 0 5px;
                min-width: 150px;
              }
              .remarks {
                margin: 30px 0;
                font-size: 14px;
                text-align: center;
              }
              .contact {
                text-align: center;
                font-size: 14px;
              }
            </style>
          </head>
          <body>
            ${printContent}
          </body>
        </html>
      `);
      doc.close();

      // 等待图片加载完成后打印
      printIframe.onload = () => {
        printIframe.contentWindow.focus();
        printIframe.contentWindow.print();
        // 打印完成后移除 iframe
        setTimeout(() => {
          document.body.removeChild(printIframe);
        }, 100);
      };
    }
  }
}
</script>

<style lang="scss" scoped>
span {
  font-size: 26px;
}

.print-container {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .6);
  position: absolute;
  left: 0;
  top: 0;
  z-index: 10009;
}

.bill-content {
  width: 1800px;
  height: 1000px;
  background: #FFFFFF;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  overflow: auto;
  padding: 50px;
  //overflow: hidden;
}

.title {
  text-align: center;
  font-size: 30px;
  margin-bottom: 30px;
}

.basic-info {
  margin-bottom: 30px;

  .info-row {
    display: flex;
    margin-bottom: 20px;

    .info-item {
      flex: 1;
      display: flex;
      align-items: center;

      .label {
        width: 160px;
        text-align: right;
        padding-right: 10px;
      }

      .value-line {
        flex: 1;
        height: 35px;
        border-bottom: 1px solid #000;
        padding: 0 5px;
        min-width: 150px;
      }
    }
  }
}

.bill-table {
  margin-bottom: 30px;
  font-size: 28px;

  .table-title {
    text-align: center;
    font-weight: bold;
    margin-bottom: 15px;
  }

  table {
    width: 100%;
    border-collapse: collapse;

    th, td {
      border: 1px solid #000;
      text-align: center;
      padding: 8px;
      font-size: 14px;
    }

    .text-left {
      text-align: left;
    }
  }

  .total-amount {
    text-align: right;
    margin-top: 15px;
    font-weight: bold;
  }
}

.footer-info {
  .payment-method {
    margin-bottom: 20px;
  }

  .signature-row {
    display: flex;
    margin-bottom: 20px;

    .signature-item {
      flex: 1;
      display: flex;
      align-items: center;

      .label2 {
        width: 160px;
        text-align: right;
        padding-right: 10px;
      }

      .value-line2 {
        flex: 1;
        height: 35px;
        border-bottom: 1px solid #000;
        padding: 0 5px;
        min-width: 150px;
      }
    }
  }

  .remarks {
    margin: 30px 0;
    font-size: 14px;
    text-align: center;
  }

  .contact {
    text-align: center;
    font-size: 14px;
  }

  .footer-btn {
    text-align: right;
  }
}

@media print {
  .print-container {
    padding: 0;
  }

  .bill-content {
    width: 100%;
    padding: 0;
  }

  .label2 {
    width: 100px;
    text-align: right;
    padding-right: 10px;
  }

  .value-line2 {
    flex: 1;
    border-bottom: 1px solid #000;
    padding: 0 5px;
    min-width: 150px;
  }
}
</style>